package com.luatos.iot.regproxy.module;

import java.io.ByteArrayInputStream;
import java.net.URLEncoder;

import org.nutz.http.Header;
import org.nutz.http.Request;
import org.nutz.http.Request.METHOD;
import org.nutz.http.Response;
import org.nutz.http.Sender;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.nutz.lang.Encoding;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.lang.util.Regex;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Ok;
import org.nutz.repo.Base64;

@At("/reg")
@Fail("http:500")
@IocBean
public class OnenetIotRegModule {

	private static Log log = Logs.get();

	@Inject
	protected PropertiesProxy conf;

	@At
	@Ok("json:tidy")
	public NutMap onenet(String dev, String key, String sign, String ranstr) {
		// 首先, 检查必要的参数
		if (Strings.isBlank(dev) || Strings.isBlank(key)) {
			log.debug("miss dev/key/sign/ranstr");
			return new NutMap("msg", "miss dev/key/sign");
		}
		if (!Regex.match("^[a-zA-z0-9]{10,20}", dev)) {
			log.info("非法的设备名称" + dev);
			return new NutMap("msg", "bad dev name");
		}
		// 获取项目的accessKey
		String accessKey = conf.get("luatos.regproxy.onenet." + key + ".accessKey");
		// 计算签名, md5算法应该是所有设备都能支持的
//		String mysign = Lang.md5(dev + key + Strings.sBlank(ranstr));
//		if (!mysign.equalsIgnoreCase(sign)) {
//			log.debugf("sign not match expect %s but %s", mysign, sign);
//			return new NutMap("msg", "sign not match");
//		}

		// 初始化SDK客户端
		Request req = Request.create("https://api.heclouds.com/mqtt/v1/devices/reg", METHOD.POST);
		req.setData(Json.toJson(new NutMap("name", dev), JsonFormat.full()));
		Header headers = Header.create();
		headers.asJsonContentType();
		req.setHeader(headers);

		// version=2018-10-31&res=products%2F123123&et=1537255523&method=sha1&sign=ZjA1NzZlMmMxYzIOTg3MjBzNjYTI2MjA4Yw%3D
		long timenow = System.currentTimeMillis() / 1000 + 30; // 当前时间+30秒
		String tmp = "version=2018-10-31&res=products%2F" + key + "&et=" + timenow + "&method=sha1&sign=";
		String strForSign = "" + timenow + '\n' + "sha1" + '\n' + "products/" + key + '\n' + "2018-10-31";
		String apisign = Base64.encodeToString(
				Lang.digest2("SHA1", new ByteArrayInputStream(strForSign.getBytes()), Base64.decode(accessKey)), false);

		headers.set("Authorization", tmp + URLEncoder.encode(apisign, Encoding.CHARSET_UTF8));
		// System.out.println(strForSign);
		// System.out.println(headers.get("Authorization"));
		// System.out.println(headers);

		Response resp = Sender.create(req).send();
		if (resp.isOK()) {
			NutMap re = Json.fromJson(NutMap.class, resp.getReader());
			return new NutMap("secret", re.getAs("data", NutMap.class).getString("key"));
		} else {
			log.debug("onenet say no " + resp.getContent());
		}

		return new NutMap("msg", "server error");
	}
}
